package com.wu.printlistfromtailtohead;

import java.util.ArrayList;
import java.util.Stack;

/**
 * 输入一个链表，按链表从尾到头的顺序返回一个ArrayList。
 */
class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> listNodes = new ArrayList<>();
        if (listNode == null) {
            return listNodes;
        }
        Stack<Integer> stack = new Stack<>();
        stack.push(listNode.val);
        ListNode cur = listNode.next;
        while (cur != null) {
            stack.push(cur.val);
            cur = cur.next;
        }
        while (!stack.empty()) {
            listNodes.add(stack.pop());
        }
        return listNodes;
    }
}
